package org.example.threadpool;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhengdp
 * @Description 带有调度功能的线程池
 * @Date 2022/12/20 20:54
 * @Created by zhengdp
 */
@Slf4j(topic = "c.TestScheduledThreadPool")
public class TestScheduledThreadPool {

    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.info("start ...");
        // 初始延迟1， 间隔时间1（并不是严格意义的间隔时间，会被执行时间挤占）
        // 任务开始 <--- 间隔时间 ---> 任务开始
        pool.scheduleAtFixedRate(() -> {
            log.info("running");
            Sleeper.sleep(2000);
        },1,1,TimeUnit.SECONDS);
        ScheduledExecutorService pool2 = Executors.newScheduledThreadPool(1);
        // delay : 每个任务 和每个任务的间隔时间，任务完成 <--- 间隔时间 ---> 任务开始
        pool2.scheduleWithFixedDelay(() -> {
            log.info("running2 ... ");
            Sleeper.sleep(2000);
        },1,1,TimeUnit.SECONDS);
    }

    @SneakyThrows
    public static void method2(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);

        pool.schedule(() -> {
            log.info("task1");
            Sleeper.sleep(2000);
        },1, TimeUnit.SECONDS);

        pool.schedule(() -> {
            log.info("task2");
        },1, TimeUnit.SECONDS);
    }
}
